from tkinter import *
import cv2
import dlib
import pathlib
import os , sys
import time
from PIL import Image,ImageTk
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))

def take_snapshot():
    print("有人给你点赞啦！")

def video_loop():
    success, img = capture.read(1)  # 从摄像头读取照片
      
    if(success):
        cv2.waitKey(30)
        image1=img
        image2=cv2.resize(img,(int(cwidth/2), int(chight/2)))
    gray_frame = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
    faces=detector(gray_frame, 1)
    (x1_,x2_,y1_,y2_,img1)=show_detection(image2, faces)
    if(x1_ != -1):
        (x1,x2,y1,y2)=(x1_,x2_,y1_,y2_)

    cv2image = cv2.cvtColor(img1, cv2.COLOR_BGR2RGBA)#转换颜色从BGR到RGBA
    current_image = Image.fromarray(cv2image)#将图像转换成Image对象
    imgtk = ImageTk.PhotoImage(image=current_image)
    panel.imgtk = imgtk
    panel.config(image=imgtk)
    root.after(1, video_loop)
def show_detection(image, faces):
    img=image
    if(len(faces)!=0):
        for (i,face) in enumerate(faces):
            cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 128, 0), 1)
            x=int((face.right()-face.left())*w)
            y2= int((face.bottom()-face.top())*w)
            y1=int(x+face.bottom()-(hight*(face.right()-face.left()+2*x)/width))
            x1=face.left()-x
            x2=face.right()+x
            ht=(hight*(face.right()-face.left()+x+x))/width
            y1=int(face.bottom()+ht*p)
            y2=int(y1-ht)
            cv2.rectangle(img, (x1, y1), (x2,y2), (0, 0, 255), 1)
        return (x1,x2,y1,y2,img)
    else:
        return (-1,0,0,0,img)


detector = dlib.get_frontal_face_detector()

capture = cv2.VideoCapture(1)    #摄像头
cwidth= 1280 #宽
chight= 960 #高
capture.set(3,cwidth)
capture.set(4,chight)
# width= 295 #宽
# hight= 413 #高
width= 390 #宽
hight= 567 #高
p=0.20 #上下比例
w=0.20 #扩展比例
def save(img,filepath,x1,y1,x2,y2):
    crop_img = img[y2:y1,x1:x2] 
    print(f"size:{x2-x1},{y1-y2}")
    filepath=str(f"{root}/{int(time.time())}.jpg")
    try:
        res = cv2.resize(crop_img,(width, hight), interpolation = cv2.INTER_CUBIC)
        cv2.imwrite(filepath,res)
        Image.open(filepath).save(filepath,None,dpi=(300.0,300.0))
        cv2.imshow("image", crop_img)
    except :
        res = None
        pass
root = Tk()
root.title("opencv + tkinter")
#root.protocol('WM_DELETE_WINDOW', detector)

panel = Label(root)  # initialize image panel
panel.pack(padx=10, pady=10)
root.config(cursor="arrow")
btn = Button(root, text="点赞!", command=take_snapshot)
btn.pack(fill="both", expand=True, padx=10, pady=10)

video_loop()

root.mainloop()
# 当一切都完成后，关闭摄像头并释放所占资源
capture.release()
cv2.destroyAllWindows()